//
//  WBRefreshControl.swift
//  mySina
//
//  Created by mac on 15/12/23.
//  Copyright © 2015年 tz. All rights reserved.
//

//自定义刷新控件
import UIKit

import SnapKit

enum WBRefreshStatue:Int {
    //默认状态
    case Normal = 0
    //用户下拉到临界值，还么有松手的状态
    case Pulling = 1
    //正在刷新的状态
    case Refreshing = 2
}

//刷新控件的高度
private let refreshVieHeight:CGFloat = 60

class WBRefreshControl: UIControl {
    //定义属性，保存上一次刷新的状态
    var oldStatue: WBRefreshStatue = .Normal
    
    //MARK: 定义外部模型属性
    var statue: WBRefreshStatue = .Normal {
        didSet {
            //根据不同的状态，显示不同的逻辑
            switch statue {
                
            case .Pulling:
//                print("准备起飞")
                //1修改提示文本
                tipLabel.text = "准备起飞"
                //2旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
//                print("正在起飞")
                tipLabel.text = "正在起飞"
                //隐藏箭头，显示转动的小菊花
                arrowIcon.hidden = true
                loadIcon.startAnimating()
                //修改contenInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += refreshVieHeight
                    self.scrollView?.contentInset = inset
                })
                //应该主动触发 control 的方法响应事件
                //MARK: 查找----------sendActionsForControlEvents
                sendActionsForControlEvents(.ValueChanged)
            case .Normal:
                //                print("下拉起飞")
                tipLabel.text = "下拉起飞"
                arrowIcon.hidden = false
                loadIcon.stopAnimating()
                //修改contentInset
                if oldStatue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= refreshVieHeight
                        self.scrollView?.contentInset = inset
                    })
                }
                
                //重置箭头的方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
            }
            //所有设置结束后，保存上一次刷新的状态
            oldStatue = statue
        }
    }
    
    //实现KVO的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        //1 获取tableView的临界值
        let insetTop = scrollView?.contentInset.top ?? 0
        let condationValue = -(refreshVieHeight + insetTop)
        //2 获取tableView的ContentOffset
        let offSetY = scrollView?.contentOffset.y ?? 0
//        print(condationValue)
//        print(offSetY)
        //MARK: 查找----------dragging
        //print(scrollView!.dragging) true下拉状态 false 上升状态
        if scrollView!.dragging {
            if statue == .Normal && offSetY < condationValue {
                //进入用户下拉临界值,还没有松手刷新的状态
                statue = .Pulling
            } else if statue == .Pulling && offSetY > condationValue {
                //进入默认状态
                statue = .Normal
            }
        } else {
            // 不是在被拉拽的状态 并且 当前的视图的statue 是 pulling状态 再执行刷新操作
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
    }
    
    //MARK: View生命周期方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //可以获得当前控件的父视图
        //获取tableView
        if let myFatherView = newSuperview as? UIScrollView {
            self.scrollView = myFatherView
            //设置KVO
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    //移除kvo观察
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //定义属性，记录父视图
    var scrollView:UIScrollView?
    
    //MARK: 重写构造方法
    override init(frame: CGRect) {
        //设置frame的大小
        let ret = CGRectMake(0, -refreshVieHeight, screenW, refreshVieHeight)
        
        super.init(frame: ret)
        
        //刷新
        setupUI()
        
        //设置颜色
        backgroundColor = UIColor.orangeColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: 设置页面 和 布局
    private func setupUI() {
        
        //添加子视图
        addSubview(arrowIcon)
        
        addSubview(tipLabel)
        
        addSubview(loadIcon)
        
        //自动布局
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(tipLabel.snp_centerY)
            
            make.right.equalTo(tipLabel.snp_left).offset(-5)
        }
        
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    func endRefreshing() {
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    //MARK: 懒加载
    //左边的图片
    private lazy var arrowIcon:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //右边的文子
    private lazy var tipLabel:UILabel = UILabel(title: "下拉起飞", color: UIColor.whiteColor(), fontSize: 14)
    
    //加载的菊花样式
    private lazy var loadIcon:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
}